import { FC, useState } from "react";
import { Button, Form, Message, Modal, Space } from "@arco-design/web-react";
import { css } from "@emotion/css";
import { useAPI } from "../../hooks/useAPI.ts";
import Password from "@arco-design/web-react/es/Input/password";
import { useMutation } from "react-query";

export interface UpdatePasswordModalProps {
  visible?: boolean;
  onClose?: () => void;
  onSuccess?: () => void;
  defaultData?: any;
}

export const UpdatePasswordModal: FC<UpdatePasswordModalProps> = ({
  visible,
  onClose,
  onSuccess,
  defaultData,
}) => {
  const api = useAPI();
  const [formRef] = Form.useForm();
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");

  const submitForm = useMutation(async () => {
    try {
      if (password !== confirmPassword) {
        Message.error("新密码和确认密码不一致");
        return;
      }

      const values = await formRef.validate();
      values.password = password;
      values.userName = defaultData?.userName;
      values.userId = defaultData?.userId;
      values.roleIds = [defaultData?.roleIds];
      values.buildingId = defaultData?.buildingId;

      await api.updateSystemUser(values);

      if (onSuccess) onSuccess();
      formRef.resetFields();
      setPassword("");
      setConfirmPassword("");

      Message.success("修改成功");
    } catch (error) {
      if (error instanceof Error) {
        Message.error(error.message);
      } else {
        Message.error("操作失败，请稍后重试");
      }
    }
  });

  return (
    <Modal
      visible={visible}
      onCancel={() => {
        formRef.resetFields();
        onClose?.();
        setPassword("");
        setConfirmPassword("");
      }}
      footer={null}
      title="修改密码"
      unmountOnExit
      mountOnEnter
    >
      <Form form={formRef}>
        <Form.Item
          label="新密码"
          rules={[
            {
              required: true,
              message: "请输入新密码",
            },
          ]}
        >
          <Password
            placeholder="请输入新密码"
            defaultValue={password}
            onChange={(e) => setPassword(e)}
          />
        </Form.Item>
        <Form.Item
          label="确认密码"
          rules={[
            {
              required: true,
              message: "请输入确认密码",
            },
          ]}
        >
          <Password
            placeholder="请再次输入密码"
            defaultValue={confirmPassword}
            onChange={(e) => setConfirmPassword(e)}
          />
        </Form.Item>

        <Space
          className={css`
            margin-top: 16px;
            padding: 12px 0;
            display: flex;
            justify-content: end;
          `}
        >
          <Button
            type="outline"
            htmlType="button"
            onClick={() => {
              formRef.resetFields();
              onClose?.();
              setPassword("");
              setConfirmPassword("");
            }}
          >
            取消
          </Button>
          <Button
            type="primary"
            htmlType="submit"
            loading={submitForm.isLoading}
            onClick={() => submitForm.mutateAsync()}
          >
            完成
          </Button>
        </Space>
      </Form>
    </Modal>
  );
};
